// Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022.

const os = require('os');
const path = require('path');

// Netlify does not support user-specified directories to cache, however they
// do allow for plug-ins, which can drive cacheing logic. We use this to cache
// our rust install and built artifacts.

// https://github.com/netlify/build#plugin-constants
//  CONFIG_PATH    Path to the Netlify configuration file
//  PUBLISH_DIR    Directory that contains the deploy-ready HTML files and assets generated by the build
//  FUNCTIONS_SRC  The directory where function source code lives
//  FUNCTIONS_DIST The directory where built serverless functions are placed before deployment
//  IS_LOCAL       Boolean indicating whether the build was run locally (Netlify CLI) or in the production CI
//  SITE_ID        The Netlify Site ID


const getCacheDirs = constants => [
	path.normalize(`${os.homedir()}/.cargo`),
	path.normalize(`${constants.PUBLISH_DIR}/../../target`),
];

module.exports = {
	async onPreBuild({ constants, utils }) {
		const cacheDirs = getCacheDirs(constants);

		console.log('Cache directories:', cacheDirs);

		const files = await utils.cache.list();
		console.log('Netlify cache list', files);

		if (await utils.cache.restore(cacheDirs)) {
			console.log('Tock build cache found -- using cache.');
		} else {
			console.warn('No cache found.');
		}
	},

	async onPostBuild({ constants, utils }) {
		const cacheDirs = getCacheDirs(constants);

		console.log('Cache directories:', cacheDirs);

		if (await utils.cache.save(cacheDirs)) {
			console.log('Stored Tock build cache.');
		} else {
			console.error('Failed to save cache.');
		}

		/* Cannot read file list after cacheing if large
		 *
     *
		 * https://community.netlify.com/t/error-with-cache-using-build-plugin-hangs-when-cache-asked-to-list-after-store/15327/6
		 * https://github.com/netlify/build/issues/1362
		 *
		const files = await utils.cache.list();
		console.log('Netlify cache list', files);
		 */
	},
}
